package com.gs.SynPatrolRep.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.gs.SynPatrolRep.R;
import com.gs.SynPatrolRep.activity.base.BaseFragmentActivity;
import com.gs.SynPatrolRep.apiresult.ApiResultData;
import com.gs.SynPatrolRep.constant.AllConstants;
import com.gs.SynPatrolRep.constant.EventCode;
import com.gs.SynPatrolRep.db.bean.Event;
import com.gs.SynPatrolRep.db.dao.DBUtil;
import com.gs.SynPatrolRep.db.dto.VersionDto;
import com.gs.SynPatrolRep.dialog.CommDialogUtils;
import com.gs.SynPatrolRep.fragment.InsightFragment;
import com.gs.SynPatrolRep.fragment.PalBillListFragment;
import com.gs.SynPatrolRep.fragment.SettingsFragment;
import com.gs.SynPatrolRep.fragment.SiteEventListFragment;
import com.gs.SynPatrolRep.presenter.MainPresenter;
import com.gs.SynPatrolRep.service.SignalRService;
import com.gs.SynPatrolRep.util.AppUtil;
import com.gs.SynPatrolRep.util.PermissionUtil;
import com.gs.SynPatrolRep.view.IMainView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends BaseFragmentActivity implements IMainView {

    private List<Fragment> fragmentList;
    private Fragment mFragment;
    private int fragmentIndex;
    private MainPresenter mPresenter;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        PermissionUtil.addPermission(this,
                new String[]{
                        Manifest.permission.BLUETOOTH,
                        Manifest.permission.VIBRATE,
                        Manifest.permission.REQUEST_INSTALL_PACKAGES,
                        Manifest.permission.FOREGROUND_SERVICE}, 1);
        mPresenter = new MainPresenter();
        mPresenter.attachView(this);
        OnClickListener onClickListener = new OnClickListener();
        fd(R.id.tv_insight).setOnClickListener(onClickListener);
        fd(R.id.tv_report).setOnClickListener(onClickListener);
        fd(R.id.tv_event).setOnClickListener(onClickListener);
        fd(R.id.tv_settings).setOnClickListener(onClickListener);
        if (savedInstanceState != null) {
            fragmentIndex = savedInstanceState.getInt(AllConstants.WHAT);
        } else {
            int what = getIntent().getIntExtra(AllConstants.WHAT, 0);
            if (what == 2) {
                fragmentIndex = 2;
            }else if (what == 1){
                fragmentIndex = 1;
            }
        }
        if (fragmentIndex == 0) {
            fragmentIndex = 1;
            showFragment(mFragment, getFragment());
            fragmentIndex = 0;
            mPresenter.getVersion();
            startService(new Intent(this, SignalRService.class));
        }
        showFragment(mFragment, getFragment());
    }

    @Override
    protected void initFragment() {
        fragmentList = new ArrayList<>();
        InsightFragment insightFragment = new InsightFragment();
        PalBillListFragment palBillListFragment = new PalBillListFragment();
        SiteEventListFragment siteEventListFragment = new SiteEventListFragment();
        SettingsFragment settingsFragment = new SettingsFragment();
        fragmentList.add(insightFragment);
        fragmentList.add(palBillListFragment);
        fragmentList.add(siteEventListFragment);
        fragmentList.add(settingsFragment);
    }

    @Override
    protected void event(Event event) {
        if (event.getWhat() == EventCode.EVENT_JUMP) {
            fragmentIndex = 1;
            showFragment(mFragment, getFragment());
        }
    }

    /**
     * 刷新時清除舊的fragment
     */
    @Override
    public void recreate() {
        try {
            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
            for (Fragment fragment : fragmentList) {
                ft.detach(fragment);
            }
            ft.commitAllowingStateLoss();
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.recreate();
    }

    private Fragment getFragment() {
        return fragmentList.get(fragmentIndex);
    }

    private void showFragment(Fragment fromFragment, Fragment toFragment) {
        if (fromFragment != toFragment) {
            mFragment = toFragment;
            FragmentManager fm = getSupportFragmentManager();
            FragmentTransaction transaction = fm.beginTransaction();
            if (fromFragment != null) {
                transaction.hide(fromFragment);
            }
            if (toFragment.isAdded()) {
                transaction.show(toFragment);
            } else {
                transaction.add(R.id.fl_content, toFragment);
            }
            transaction.commit();
        }
    }

    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(AllConstants.WHAT, fragmentIndex);
    }

    @Override
    public void onGetVersionSuccess(final ApiResultData<VersionDto> apiResultData) {
        if (apiResultData.getStatus() == 2000) {
            if (apiResultData.getData() != null) {
                int newVersion;
                int myVersion;
                try {
                    newVersion = Integer.parseInt(apiResultData.getData().getVersion().replace(".", ""));
                    myVersion = Integer.parseInt(AppUtil.getInstance().getVersion().replace(".", ""));
                } catch (NumberFormatException e) {
                    Toast.makeText(MainActivity.this, R.string.version_error, Toast.LENGTH_LONG).show();
                    e.printStackTrace();
                    return;
                }
                if (newVersion > myVersion) {
                    CommDialogUtils.showDialog(MainActivity.this, getString(R.string.new_version),
                            apiResultData.getData().getDesc(), R.string.download,
                            new CommDialogUtils.DialogClickListener() {
                                @Override
                                public void cancelClick() {

                                }

                                @Override
                                public void okClick() {
                                    String fileName = apiResultData.getData().getOutputFile();
                                    File file = new File(MainActivity.this.getCacheDir(), fileName);
                                    // 已下載過安裝包
                                    if (AppUtil.getInstance().fileIsExists(file)) {
                                        AppUtil.getInstance().installApk(MainActivity.this, file);
                                    } else {
                                        // 展示進度條
                                        CommDialogUtils.showProgressDialog(MainActivity.this);
                                        mPresenter.downloadFile(fileName, file);
                                    }
                                }
                            });
                }
            }
        }
    }

    @Override
    public void onGetVersionFails(Exception e) {

    }

    @Override
    public void onDownloadFileSuccess(File file) {
        AppUtil.getInstance().installApk(MainActivity.this, file);
        CommDialogUtils.dismissProDialog();
    }

    @Override
    public void onDownloadProgress(int progress) {
        CommDialogUtils.setProgress(progress);
    }

    @Override
    public void onDownloadFails(Exception e) {
        Toast.makeText(MainActivity.this, R.string.download_error, Toast.LENGTH_LONG).show();
        CommDialogUtils.dismissProDialog();
    }

    class OnClickListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.tv_insight:
                    fragmentIndex = 0;
                    break;
                case R.id.tv_report:
                    fragmentIndex = 1;
                    break;
                case R.id.tv_event:
                    fragmentIndex = 2;
                    break;
                case R.id.tv_settings:
                    fragmentIndex = 3;
                    break;
            }
            showFragment(mFragment, getFragment());
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        DBUtil.getInstance().closeConnection();
        if (mPresenter != null) {
            mPresenter.detachView();
        }
    }
}